package com.android.equipment.ui

import android.annotation.SuppressLint
import android.os.Bundle
import com.android.equipment.R
import com.android.equipment.adapter.UpdateConfigAdapter
import com.android.equipment.base.BaseActivity
import com.android.equipment.dao.operate.DaoConfigModel
import com.android.equipment.databinding.ActivityUpdateConfigBinding
import com.blankj.utilcode.util.ToastUtils
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.gyf.immersionbar.ImmersionBar

class UpdateConfigActivity : BaseActivity<ActivityUpdateConfigBinding>() {

    val adapter: UpdateConfigAdapter by lazy {
        UpdateConfigAdapter(R.layout.item_config)
    }

    override fun setLayoutContent() = ActivityUpdateConfigBinding.inflate(layoutInflater)

    override fun initView(savedInstanceState: Bundle?) {
        initRecycler()
    }


    override fun initData() {
        val deviceModelId = intent.getLongExtra("deviceModelId", 0)
        val configModels =
            DaoConfigModel.getInstance().getConfigModelByDeviceModelId(deviceModelId)
        adapter.setList(configModels)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initEvent() {
        super.initEvent()
        binding.mTitleBar.leftView.setOnClickListener {
            mSwipeBackHelper.backward()
        }

        binding.tvSubmit.setOnClickListener {
            adapter.data.forEach { configModel ->
                DaoConfigModel.getInstance().updateConfigModel(configModel)
            }
            adapter.notifyDataSetChanged()
            ToastUtils.showShort("保存成功")
            mSwipeBackHelper.backward()
        }
    }

    private fun initRecycler() {
        val flex = FlexboxLayoutManager(this).apply {
            flexDirection = FlexDirection.ROW
            flexWrap = FlexWrap.WRAP
            justifyContent = JustifyContent.FLEX_START
        }
        binding.rvConfig.layoutManager = flex
        binding.rvConfig.adapter = adapter

        adapter.setOnItemClickListener { adapter, view, position ->
            val configModel = (adapter as UpdateConfigAdapter).getItem(position)
            configModel.is_show = if (configModel.is_show == 1) 0 else 1
            adapter.notifyItemChanged(position)
        }
    }


    override fun setStatusBar() {
        ImmersionBar.with(this)
            .statusBarColor(R.color.F8F9FA)
            .statusBarDarkFont(true)
            .titleBar(binding.mTitleBar)
            .init()
    }
}